package com.wpf.system.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wpf.system.common.response.ResultUtils;
import com.wpf.system.common.response.ResultVO;
import com.wpf.system.entity.Equipment;
import com.wpf.system.entity.EquipmentRent;
import com.wpf.system.entity.Orders;
import com.wpf.system.entity.dto.BookRentBuySearchDTO;
import com.wpf.system.entity.vo.EquipmentRentVO;
import com.wpf.system.entity.vo.PageVO;
import com.wpf.system.service.*;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/api/equipmentRent")
public class EquipmentRentController {

    @Resource
    private EquipmentRentService equipmentRentService;

    @Resource
    private OrdersService ordersService;

    @Resource
    private EquipmentService equipmentService;

    @Resource
    private BalanceJournalService balanceJournalService;

    @Resource
    private PointJournalService pointJournalService;

    @GetMapping("/chart")
    public ResultVO getEquipmentRentChart(@RequestParam(value = "date",required=false) String date){
        return ResultUtils.success("请求租借图表数据成功",equipmentRentService.getEquipmentRentChartData(date));
    }

    @GetMapping("/out/{uid}")
    public Long checkTimeOut(@PathVariable("uid") Long uid ){ return equipmentRentService.getOutTimeRent(uid);}

    @GetMapping("/list")
    public PageVO<EquipmentRentVO> getAllEquipmentRent(
            @RequestParam(value = "no",required=false) String no,
            @RequestParam(value = "uid",required=false) Long uid,
            @RequestParam(value = "name",required=false) String name,
            @RequestParam(value = "nid",required=false) String nid,
            @RequestParam(value = "username",required=false) String username,
            @RequestParam(value = "phone",required=false) String phone,
            @RequestParam(value = "startTime",required=false) String startTime,
            @RequestParam(value = "endTime",required=false) String endTime,
            @RequestParam(value = "page",required=false) int page,
            @RequestParam(value = "pageSize",required=false) int pageSize
    ){
        BookRentBuySearchDTO bookRentBuySearchDTO = new BookRentBuySearchDTO();
        bookRentBuySearchDTO.setNo(no);
        bookRentBuySearchDTO.setUid(uid);
        bookRentBuySearchDTO.setName(name);
        bookRentBuySearchDTO.setNid(nid);
        bookRentBuySearchDTO.setUsername(username);
        bookRentBuySearchDTO.setPhone(phone);
        bookRentBuySearchDTO.setStartTime(startTime);
        bookRentBuySearchDTO.setEndTime(endTime);
        bookRentBuySearchDTO.setPageSize(pageSize);
        //手动分页需要注意分页公式
        bookRentBuySearchDTO.setPage(Math.max((page - 1) * pageSize,0));

        List<EquipmentRentVO> list = equipmentRentService.getAllEquipmentRent(bookRentBuySearchDTO);
        bookRentBuySearchDTO.setPage(null);
        bookRentBuySearchDTO.setPageSize(null);
        int total = equipmentRentService.getAllEquipmentRent(bookRentBuySearchDTO).size();
        PageVO<EquipmentRentVO> equipmentRentListVO = new PageVO<>();
        equipmentRentListVO.setList(list);
        equipmentRentListVO.setTotal(total);
        return equipmentRentListVO;
    }

    @PostMapping
    public ResultVO addEquipmentRent(@RequestBody EquipmentRent equipmentRent){
        Equipment equipment = equipmentService.getById(equipmentRent.getEid());
        if(equipment.getNumber()>=equipmentRent.getNumber()){
            equipment.setNumber(equipment.getNumber()-equipmentRent.getNumber());
            if(Convert.toBool(equipmentService.updateById(equipment))){
                if(Convert.toBool(equipmentRentService.save(equipmentRent))){
                    return ResultUtils.success("提交租赁信息成功！请在1分钟内请确认订单无误！",equipmentRent);
                }
            }
        }
        return ResultUtils.error("器材库存不足！提交租赁信息失败！");
    }

    @PutMapping
    public ResultVO editEquipmentRentStatus(@RequestBody EquipmentRent equipmentRent){
        int beforeUpdateStatus = equipmentRentService.getById(equipmentRent.getId()).getStatus();
        Orders orders = ordersService.getById(equipmentRent.getOid());
        boolean flag;
        String msg = null;
        //如果是未支付的订单取消子项，则整个订单取消
        if(orders.getStatus()==0){
            equipmentRentService.list(new LambdaQueryWrapper<EquipmentRent>().eq(EquipmentRent::getOid,orders.getId())).forEach(item->{
                item.setStatus(equipmentRent.getStatus());
                equipmentRentService.updateById(item);
            });
            orders.setStatus(2);
            orders.setCost(BigDecimal.valueOf(0));
            orders.setPoint(0L);
            flag = ordersService.updateById(orders);
            if(flag){
                msg = "已成功取消整个租赁订单！";
            }else{
                msg = "取消整个租赁订单失败！";
            }
        }else{
            flag = equipmentRentService.updateById(equipmentRent);
            switch (equipmentRent.getStatus()){
                case 2:
                    if(flag){
                        msg = "领取码正确！用户可拿取器材";
                    }else{
                        msg = "领取码错误！";
                    }
                    break;
                case 3:
                case 4:
                    if(flag){
                        //退还库存
                        Equipment equipment = equipmentService.getById(equipmentRent.getEid());
                        equipment.setNumber(equipment.getNumber()+equipmentRent.getNumber());
                        equipmentService.updateById(equipment);
                        if(equipmentRent.getStatus()==3){
                            msg = "返还成功！";
                        }else if(equipmentRent.getStatus()==4){
                            msg = "返还成功！";
                        }

                    }else{
                        if(equipmentRent.getStatus()==3){
                            msg = "返还失败！请再次尝试";
                        }else if(equipmentRent.getStatus()==4){
                            msg = "返还失败！请再次尝试！";
                        }
                    }
                    break;
                case 7:
                case 8:
                    if(flag){
                        if(ObjectUtil.isNotNull(orders)&&orders.getStatus()!=0){
                            if(orders.getPoint()>0 || orders.getCost().compareTo(BigDecimal.valueOf(0))==1&&beforeUpdateStatus!=0){
                                if(orders.getPoint()>0){
                                    pointJournalService.pointInto(orders,1);
                                }
                                if(orders.getCost().compareTo(BigDecimal.valueOf(0))==1&&beforeUpdateStatus!=0){
                                    balanceJournalService.balanceInto(orders,1,equipmentRent.getId());
                                }
                            }
                        }
                        //退还库存
                        Equipment equipment = equipmentService.getById(equipmentRent.getEid());
                        equipment.setNumber(equipment.getNumber()+equipmentRent.getNumber());
                        equipmentService.updateById(equipment);
                        if(equipmentRent.getStatus()==7){
                            msg = "取消租赁成功！";
                        }else {
                            msg = "撤销预约成功！";
                        }
                    }else if(equipmentRent.getStatus()==8){
                        if(equipmentRent.getStatus()==7){
                            msg = "取消租赁失败！";
                        }else if(equipmentRent.getStatus()==8){
                            msg = "撤销预约失败！";
                        }
                    }
                    //关联订单关闭
                    orders.setStatus(2);
                    ordersService.updateById(orders);
                    break;
                case 9:
                    if(flag){
                        msg = "请提示用户支付超时费用！";
                    }else{
                        msg = "请再次尝试！";
                    }
                    break;
                case 10:
                    if(flag){
                        msg = "待管理员确认归还器材！";
                    }else{
                        msg = "请再次尝试！";
                    }
                    break;
            }
        }

        if(flag){
            return ResultUtils.success(msg);
        }else{
            return ResultUtils.error(msg);
        }
    }

    @DeleteMapping("/{id}")
    public ResultVO deleteEQRentById(@PathVariable("id") Long id){
        //退还库存
        EquipmentRent equipmentRent = equipmentRentService.getById(id);
        Equipment equipment = equipmentService.getById(equipmentRent.getEid());
        equipment.setNumber(equipment.getNumber()+equipmentRent.getNumber());
        if(equipmentService.updateById(equipment)){
            if (Convert.toBool(equipmentRentService.deleteEQRentById(id))){
                return ResultUtils.success("取消租赁订单成功！");
            }
        }
        return ResultUtils.error("取消租赁订单失败！");
    }

}
